home *** CD-ROM | disk | FTP | other *** search
/ Visual Cafe 3 / Visual Cafe 3.ISO / Vcafe / Sample.bin / TableSorter.java < prev    next >
Text File  |  1998-06-30  |  12KB  |  346 lines

  1. /*
  2.  * @(#)TableSorter.java    1.5 97/12/17
  3.  *
  4.  * Copyright (c) 1997 Sun Microsystems, Inc. All Rights Reserved.
  5.  *
  6.  * This software is the confidential and proprietary information of Sun
  7.  * Microsystems, Inc. ("Confidential Information").  You shall not
  8.  * disclose such Confidential Information and shall use it only in
  9.  * accordance with the terms of the license agreement you entered into
  10.  * with Sun.
  11.  *
  12.  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
  13.  * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  14.  * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  15.  * PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR ANY DAMAGES
  16.  * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
  17.  * THIS SOFTWARE OR ITS DERIVATIVES.
  18.  *
  19.  */
  20.  
  21. /**
  22.  * A sorter for TableModels. The sorter has a model (conforming to TableModel) 
  23.  * and itself implements TableModel. TableSorter does not store or copy 
  24.  * the data in the TableModel, instead it maintains an array of 
  25.  * integers which it keeps the same size as the number of rows in its 
  26.  * model. When the model changes it notifies the sorter that something 
  27.  * has changed eg. "rowsAdded" so that its internal array of integers 
  28.  * can be reallocated. As requests are made of the sorter (like 
  29.  * getValueAt(row, col) it redirects them to its model via the mapping 
  30.  * array. That way the TableSorter appears to hold another copy of the table 
  31.  * with the rows in a different order. The sorting algorthm used is stable 
  32.  * which means that it does not move around rows when its comparison 
  33.  * function returns 0 to denote that they are equivalent. 
  34.  *
  35.  * @version 1.5 12/17/97
  36.  * @author Philip Milne
  37.  */
  38.  
  39. import java.util.*;
  40.  
  41. import com.sun.java.swing.table.TableModel;
  42. import com.sun.java.swing.event.TableModelEvent;
  43.  
  44. // Imports for picking up mouse events from the JTable. 
  45.  
  46. import java.awt.event.MouseAdapter;
  47. import java.awt.event.MouseEvent;
  48. import java.awt.event.InputEvent;
  49. import com.sun.java.swing.JTable;
  50. import com.sun.java.swing.table.JTableHeader;
  51. import com.sun.java.swing.table.TableColumn;
  52. import com.sun.java.swing.table.TableColumnModel;
  53.  
  54. public class TableSorter extends TableMap
  55. {
  56.     int             indexes[];
  57.     Vector          sortingColumns = new Vector();
  58.     boolean         ascending = true;
  59.     int compares;
  60.  
  61.     public TableSorter()
  62.     {
  63.         indexes = new int[0]; // For consistency.        
  64.     }
  65.  
  66.     public TableSorter(TableModel model)
  67.     {
  68.         setModel(model);
  69.     }
  70.  
  71.     public void setModel(TableModel model) {
  72.         super.setModel(model); 
  73.         reallocateIndexes(); 
  74.     }
  75.  
  76.     public int compareRowsByColumn(int row1, int row2, int column)
  77.     {
  78.         Class type = model.getColumnClass(column);
  79.         TableModel data = model;
  80.  
  81.         // Check for nulls
  82.  
  83.         Object o1 = data.getValueAt(row1, column);
  84.         Object o2 = data.getValueAt(row2, column); 
  85.  
  86.         // If both values are null return 0
  87.         if (o1 == null && o2 == null) {
  88.             return 0; 
  89.         }
  90.         else if (o1 == null) { // Define null less than everything. 
  91.             return -1; 
  92.         } 
  93.         else if (o2 == null) { 
  94.             return 1; 
  95.         }
  96.  
  97. /* We copy all returned values from the getValue call in case
  98. an optimised model is reusing one object to return many values.
  99. The Number subclasses in the JDK are immutable and so will not be used in 
  100. this way but other subclasses of Number might want to do this to save 
  101. space and avoid unnecessary heap allocation. 
  102. */
  103.         if (type.getSuperclass() == java.lang.Number.class)
  104.             {
  105.                 Number n1 = (Number)data.getValueAt(row1, column);
  106.                 double d1 = n1.doubleValue();
  107.                 Number n2 = (Number)data.getValueAt(row2, column);
  108.                 double d2 = n2.doubleValue();
  109.  
  110.                 if (d1 < d2)
  111.                     return -1;
  112.                 else if (d1 > d2)
  113.                     return 1;
  114.                 else
  115.                     return 0;
  116.             }
  117.         else if (type == java.util.Date.class)
  118.             {
  119.                 Date d1 = (Date)data.getValueAt(row1, column);
  120.                 long n1 = d1.getTime();
  121.                 Date d2 = (Date)data.getValueAt(row2, column);
  122.                 long n2 = d2.getTime();
  123.  
  124.                 if (n1 < n2)
  125.                     return -1;
  126.                 else if (n1 > n2)
  127.                     return 1;
  128.                 else return 0;
  129.             }
  130.         else if (type == String.class)
  131.             {
  132.                 String s1 = (String)data.getValueAt(row1, column);
  133.                 String s2    = (String)data.getValueAt(row2, column);
  134.                 int result = s1.compareTo(s2);
  135.  
  136.                 if (result < 0)
  137.                     return -1;
  138.                 else if (result > 0)
  139.                     return 1;
  140.                 else return 0;
  141.             }
  142.         else if (type == Boolean.class)
  143.             {
  144.                 Boolean bool1 = (Boolean)data.getValueAt(row1, column);
  145.                 boolean b1 = bool1.booleanValue();
  146.                 Boolean bool2 = (Boolean)data.getValueAt(row2, column);
  147.                 boolean b2 = bool2.booleanValue();
  148.  
  149.                 if (b1 == b2)
  150.                     return 0;
  151.                 else if (b1) // Define false < true
  152.                     return 1;
  153.                 else
  154.                     return -1;
  155.             }
  156.         else
  157.             {
  158.                 Object v1 = data.getValueAt(row1, column);
  159.                 String s1 = v1.toString();
  160.                 Object v2 = data.getValueAt(row2, column);
  161.                 String s2 = v2.toString();
  162.                 int result = s1.compareTo(s2);
  163.  
  164.                 if (result < 0)
  165.                     return -1;
  166.                 else if (result > 0)
  167.                     return 1;
  168.                 else return 0;
  169.             }
  170.     }
  171.  
  172.     public int compare(int row1, int row2)
  173.     {
  174.         compares++;
  175.         for(int level = 0; level < sortingColumns.size(); level++)
  176.             {
  177.                 Integer column = (Integer)sortingColumns.elementAt(level);
  178.                 int result = compareRowsByColumn(row1, row2, column.intValue());
  179.                 if (result != 0)
  180.                     return ascending ? result : -result;
  181.             }
  182.         return 0;
  183.     }
  184.  
  185.     public void  reallocateIndexes()
  186.     {
  187.         int rowCount = model.getRowCount();
  188.  
  189.         // Set up a new array of indexes with the right number of elements
  190.         // for the new data model.
  191.         indexes = new int[rowCount];
  192.  
  193.         // Initialise with the identity mapping.
  194.         for(int row = 0; row < rowCount; row++)
  195.             indexes[row] = row;
  196.     }
  197.  
  198.     public void tableChanged(TableModelEvent e)
  199.     {
  200.     System.out.println("Sorter: tableChanged"); 
  201.         reallocateIndexes();
  202.  
  203.         super.tableChanged(e);
  204.     }
  205.  
  206.     public void checkModel()
  207.     {
  208.         if (indexes.length != model.getRowCount()) {
  209.             System.err.println("Sorter not informed of a change in model.");
  210.         }
  211.     }
  212.  
  213.     public void  sort(Object sender)
  214.     {
  215.         checkModel();
  216.  
  217.         compares = 0;
  218.         // n2sort();
  219.         // qsort(0, indexes.length-1);
  220.         shuttlesort((int[])indexes.clone(), indexes, 0, indexes.length);
  221.         System.out.println("Compares: "+compares);
  222.     }
  223.  
  224.     public void n2sort() {
  225.         for(int i = 0; i < getRowCount(); i++) {
  226.             for(int j = i+1; j < getRowCount(); j++) {
  227.                 if (compare(indexes[i], indexes[j]) == -1) {
  228.                     swap(i, j);
  229.                 }
  230.             }
  231.         }
  232.     }
  233.  
  234.     // This is a home-grown implementation which we have not had time
  235.     // to research - it may perform poorly in some circumstances. It
  236.     // requires twice the space of an in-place algorithm and makes
  237.     // NlogN assigments shuttling the values between the two
  238.     // arrays. The number of compares appears to vary between N-1 and
  239.     // NlogN depending on the initial order but the main reason for
  240.     // using it here is that, unlike qsort, it is stable.
  241.     public void shuttlesort(int from[], int to[], int low, int high) {
  242.         if (high - low < 2) {
  243.             return;
  244.         }
  245.         int middle = (low + high)/2;
  246.         shuttlesort(to, from, low, middle);
  247.         shuttlesort(to, from, middle, high);
  248.  
  249.         int p = low;
  250.         int q = middle;
  251.  
  252.         /* This is an optional short-cut; at each recursive call,
  253.         check to see if the elements in this subset are already
  254.         ordered.  If so, no further comparisons are needed; the
  255.         sub-array can just be copied.  The array must be copied rather
  256.         than assigned otherwise sister calls in the recursion might
  257.         get out of sinc.  When the number of elements is three they
  258.         are partitioned so that the first set, [low, mid), has one
  259.         element and and the second, [mid, high), has two. We skip the
  260.         optimisation when the number of elements is three or less as
  261.         the first compare in the normal merge will produce the same
  262.         sequence of steps. This optimisation seems to be worthwhile
  263.         for partially ordered lists but some analysis is needed to
  264.         find out how the performance drops to Nlog(N) as the initial
  265.         order diminishes - it may drop very quickly.  */
  266.  
  267.         if (high - low >= 4 && compare(from[middle-1], from[middle]) <= 0) {
  268.             for (int i = low; i < high; i++) {
  269.                 to[i] = from[i];
  270.             }
  271.             return;
  272.         }
  273.  
  274.         // A normal merge. 
  275.  
  276.         for(int i = low; i < high; i++) {
  277.             if (q >= high || (p < middle && compare(from[p], from[q]) <= 0)) {
  278.                 to[i] = from[p++];
  279.             }
  280.             else {
  281.                 to[i] = from[q++];
  282.             }
  283.         }
  284.     }
  285.  
  286.     public void swap(int i, int j) {
  287.         int tmp = indexes[i];
  288.         indexes[i] = indexes[j];
  289.         indexes[j] = tmp;
  290.     }
  291.  
  292.     // The mapping only affects the contents of the data rows.
  293.     // Pass all requests to these rows through the mapping array: "indexes".
  294.  
  295.     public Object getValueAt(int aRow, int aColumn)
  296.     {
  297.         checkModel();
  298.         return model.getValueAt(indexes[aRow], aColumn);
  299.     }
  300.  
  301.     public void setValueAt(Object aValue, int aRow, int aColumn)
  302.     {
  303.         checkModel();
  304.         model.setValueAt(aValue, indexes[aRow], aColumn);
  305.     }
  306.  
  307.     public void sortByColumn(int column) {
  308.         sortByColumn(column, true);
  309.     }
  310.  
  311.     public void sortByColumn(int column, boolean ascending) {
  312.         this.ascending = ascending;
  313.         sortingColumns.removeAllElements();
  314.         sortingColumns.addElement(new Integer(column));
  315.         sort(this);
  316.         super.tableChanged(new TableModelEvent(this)); 
  317.     }
  318.  
  319.     // There is no-where else to put this. 
  320.     // Add a mouse listener to the Table to trigger a table sort 
  321.     // when a column heading is clicked in the JTable. 
  322.     public void addMouseListenerToHeaderInTable(JTable table) { 
  323.         final TableSorter sorter = this; 
  324.         final JTable tableView = table; 
  325.         tableView.setColumnSelectionAllowed(false); 
  326.         MouseAdapter listMouseListener = new MouseAdapter() {
  327.             public void mouseClicked(MouseEvent e) {
  328.                 TableColumnModel columnModel = tableView.getColumnModel();
  329.                 int viewColumn = columnModel.getColumnIndexAtX(e.getX()); 
  330.                 int column = tableView.convertColumnIndexToModel(viewColumn); 
  331.                 if(e.getClickCount() == 1 && column != -1) {
  332.                     System.out.println("Sorting ..."); 
  333.                     int shiftPressed = e.getModifiers()&InputEvent.SHIFT_MASK; 
  334.                     boolean ascending = (shiftPressed == 0); 
  335.                     sorter.sortByColumn(column, ascending); 
  336.                 }
  337.              }
  338.          };
  339.         JTableHeader th = tableView.getTableHeader(); 
  340.         th.addMouseListener(listMouseListener); 
  341.     }
  342.  
  343.  
  344.  
  345. }
  346.